package shared.runtime

import org.jgroups._
import shared.file._
import shared.message.chat._
import shared.message.query._
import shared.message.GreetingsMessage
import shared.runtime._

class MessageReceiver(val runtime: Runtime) extends Receiver {

  private var state: Array[Byte] = new Array[Byte](0)
  
  def block = {}
  
  def suspect(a: Address) = {}
  
  def viewAccepted(v: View) = {
    runtime.channel.totalClients = v.getMembers.size
  }
  
  def setState(st: Array[Byte]) = { this.state = st }
  
  def getState = state
  
  def receive(m: Message) = {
    m.getObject match {
      case ChatMessage(sender, message) => runtime.chatListeners.foreach{ _.messageReceived(sender, message) }
      
      case gm:GreetingsMessage => {
        runtime.channel.send(m.getSrc, GreetingsMessage(runtime.username+"@"+runtime.host, gm.id))
        runtime.addNode(new AddressInformation(m.getSrc, gm.host))
      }
      
      case LinkMessage(host, port, file, description) => runtime.chatListeners.foreach{ _.linkReceived(host, port, file, description)}
      
      case qm: QueryMessage => qm.handle(runtime.filesystem).foreach {runtime.channel.send(m.getSrc, _)}
      
      case em: EnquiryMessage => runtime.channel.send(m.getSrc, em.handle(runtime.filesystem))
      
      case fir:FileInfoRequest => runtime.channel.send(m.getSrc, fir.handle(runtime))
      
      case r: shared.message.ResponseMessage => runtime.responseHandler.handleResponse(r)
      
      case x:Any => println("nothing to do with: " + x)
    }
  }
  
}
